package com.open.api.util;

import com.open.api.model.ResultModel;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class MyImageUtil {
    public static ResultModel GetImageStr(String imgFile)
    {
        ResultModel resultModel=new ResultModel();
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg(e.getMessage());
            return resultModel;
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str=encoder.encode(data);
        resultModel.setSuccess(true);
        resultModel.setData(base64Str);
        return resultModel;//返回Base64编码过的字节数组字符串
    }

    public static ResultModel GenerateImage(String base64str,String savepath)
    {
        ResultModel resultModel=new ResultModel();
        //对字节数组字符串进行Base64解码并生成图片
        //图像数据为空
        if (base64str == null) {
            resultModel.setSuccess(false);
            resultModel.setErrorCode("1");
            resultModel.setErrorMsg("图像数据为空");
            return resultModel;
        }
        // System.out.println("开始解码");
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            //  System.out.println("解码完成");
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
             System.out.println("开始生成图片");
            //生成jpeg图片
            OutputStream out = new FileOutputStream(savepath);
            out.write(b);
            out.flush();
            out.close();
        }
        catch (Exception e)
        {
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg(e.getMessage());
            return resultModel;
        }
        resultModel.setSuccess(true);
        return resultModel;
    }
}
